<?php
include "Task.php";
include "TaskGoing.php";
include "TaskState.php";

class TaskDAO extends DataLayer {
	private		$taskStates;
 		
	/**
	* @desc Construtor da Classe
 	*/
	function __construct($lk){
		$this->lk			= $lk;
		$this->taskStates	= array("Não Iniciada" => 0, "Em Desenvolvimento" => 0, "Finalizado" => 1);
	}

	public function getTasks($id=0, $idProject, $idSprint=0, $idBacklogItem=0, $idTaskState=0, $idUser=0, $page=0){
	
		$this->sql ="	SELECT 
							SQL_CALC_FOUND_ROWS
							t.id_tarefa, t.id_backlog_item, t.id_usuario_criador, t.id_usuario_responsavel, t.id_tarefa_estado, t.id_sprint, t.id_tarefa_requisito, t.nome, t.custo_estimado, t.ordem, t.cor, t.descricao, DATE_FORMAT(t.data_inicio, '%d/%m/%Y') data_inicio, DATE_FORMAT(t.data_limite, '%d/%m/%Y') data_limite, DATE_FORMAT(t.data_finalizacao, '%d/%m/%Y') data_finalizacao, t.status, bi.prioridade_classe priorityClass, bi.prioridade priority, u.nome nameUserOwner, bi.nome nameBacklogItem, s.ordem sprintOrder
						FROM 
							tarefas t
						INNER JOIN
							backlog_itens bi on bi.id_backlog_item = t.id_backlog_item
						INNER JOIN
							usuarios u on u.id_usuario = t.id_usuario_responsavel
						INNER JOIN
							sprints s on s.id_sprint = t.id_sprint
						WHERE 
							t.status <> 0 AND s.id_projeto = ".$idProject;

		if($id > 0)						
			$this->sql .= " and t.id_tarefa = ".$id;

		if($idSprint > 0)						
			$this->sql .= " and t.id_sprint = ".$idSprint;

		if($idBacklogItem > 0)						
			$this->sql .= " and t.id_backlog_item = ".$idBacklogItem;

		if($idTaskState > 0)
			$this->sql .= " and t.id_tarefa_estado = ".$idTaskState;

		if($idUser > 0)
			$this->sql .= " and u.id_usuario = ".$idUser;
		
		
		$this->sql .= " ORDER BY t.id_tarefa_estado ASC, t.ordem ASC";

		if($page > 0){
			$page = (int)$page;
			$page--;
			if($page < 0)
				$page = 0;
			else
				$page *= PAGINATION;

			$this->sql .= " LIMIT ".$page.",".PAGINATION;
		}
		
		$this->result = parent::select($this->sql);
		$taskList = NULL;
		
		if(count($this->result) > 0){
			$i = 0;
			foreach($this->result as $row){
				$taskList[$i] = new Task();				
				$taskList[$i]->setDadosDB($row);				

				$i++;
			}
		}
		
		return $taskList;
	}

	public function save(Task $obj){
		if($obj != NULL){
			$dbObj = $obj->fieldsDBObj;
			unset($dbObj["id_tarefa"]);
			if($obj->id > 0){
				parent::update("tarefas",$dbObj,"id_tarefa = ".$obj->id);
				return $obj->id;
			}else{
				return parent::insert("tarefas",$dbObj,"data");
			}
		}else{
			return 0;
		}
	}

	public function changeOrder($idSprint,$listTasks){
		$this->result = 0;

		if($idSprint > 0 && count($listTasks) > 0){
			$order = 0;

			foreach($listTasks as $idTask){				
				parent::update("tarefas", array("ordem" => $order), "id_tarefa=".$idTask." AND id_sprint=".$idSprint);
				$order++;
			}

			return 1;
		}

		return 0;
	}

	public function getAnnexes($id=0, $idTask=0){
		$this->sql ="	SELECT 
							ta.id_tarefa_arquivo idTaskFile, ta.id_tarefa idTask, ta.id_usuario idUser, ta.titulo title, ta.extensao extension, ta.data date, ta.status
						FROM 
							tarefas_arquivos ta						
						WHERE 
							 ta.status <> 0";

		if($id > 0)						
			$this->sql .= " AND ta.id_tarefa_arquivo = ".$id;

		if($idTask > 0)						
			$this->sql .= " AND ta.id_tarefa = ".$idTask;

		
		$this->result = parent::select($this->sql);

		return $this->result;
	}

	public function saveAttach($id,$idUser,$listFiles){
		$this->result	= 0;
		$pathTempDir	= DIRETORIO."files/temp/";
		$pathTaskDir	= DIRETORIO."files/tasks/";

		if($id > 0 && count($listFiles) > 0){
			$countSuccess = 0;

			foreach($listFiles as $row){
				$dbObj['id_tarefa']	= $id;
				$dbObj['id_usuario']= $idUser;
				$dbObj['titulo']	= $row['title'];
				$dbObj['extensao']	= $row['extension'];
				
				$idFile = parent::insert("tarefas_arquivos", $dbObj, "data");

				if(!is_dir($pathTaskDir.$id)){
					mkdir($pathTaskDir.$id, 0775);
				}

				if($idFile > 0){
					$pathDestinationFile = $pathTaskDir.$id."/".$idFile.".".$row["extension"];

					if(copy($pathTempDir.$row["file"],$pathDestinationFile)){
						$countSuccess++;
						unlink($pathTempDir.$row["file"]);
					}
				}

				$dbObj = null;
			}
			
			if(count($listFiles) == $countSuccess)
				$this->result = 1;
			else
				$this->result = -1;
		}

		return $this->result;
	}

	public function deleteAttach($id){
		if($id > 0){
			$dados["status"] = 0;
			return parent::update("tarefas_arquivos", $dados, "id_tarefa_arquivo=".$id, "data");		
		}

		return 0;
	}

	public function deleteTask($id, $idProject){
		if($id > 0 && $idProject > 0){
			$rsTask = $this->getTasks($id,$idProject);

			if(count($rsTask) > 0){				
				$dados["status"] = 0;
				return parent::update("tarefas", $dados, "id_tarefa=".$id, "data");		
			}
		}

		return 0;
	}

	public function checkEndSprint($idProject, $idSprint){
		if($idProject > 0 && $idSprint > 0){
			$this->sql = "	SELECT
								t.* 
							FROM
								tarefas t
							INNER JOIN
								tarefas_estados te on te.final = 0 AND te.id_projeto = ".$idProject."
							WHERE 
								t.id_tarefa_estado = te.id_tarefa_estado AND t.status = 1 AND t.id_sprint = ".$idSprint;

			$this->result = parent::select($this->sql);

			if(count($this->result) == 0){
				$objSprintDAO = new SprintDAO($this->lk);
				return $objSprintDAO->setEndSprint($idProject, $idSprint);
			}
		}

		return false;
	}

/******************************************************************************************************************
Estado das Tarefas Functions
******************************************************************************************************************/
	public function getTaskStateInit($idProject){
		$result = 0;

		if($idProject > 0){
			$this->sql = "	SELECT
								t.id_tarefa_estado idTaskState
							FROM
								tarefas_estados t
							WHERE 
								t.ordem = 1 AND t.id_projeto = ".$idProject;

			$this->result = parent::select($this->sql);

			if(count($this->result) > 0){
				$result = $this->result[0]->idTaskState;
			}			
		}

		return $result;
	}

	public function saveTaskState(TaskState $obj){
		if($obj != NULL){
			$dbObj = $obj->fieldsDBObj;
			unset($dbObj["id_tarefa_estado"]);
			if($obj->id > 0){
				parent::update("tarefas_estados",$dbObj,"id_tarefa_estado = ".$obj->id);
				return $obj->id;
			}else{
				return parent::insert("tarefas_estados",$dbObj,"data");
			}
		}else{
			return 0;
		}
	}

	public function createTasksState($idProject){
		$order = 0;
		$objTaskState = new TaskState();
		$objTaskState->idUser	 = $_SESSION["USER"]->id;
		$objTaskState->idProject = $idProject;

		foreach($this->taskStates as $key => $row){
			$objTaskState->name = $key;
			$objTaskState->order = ++$order;
			$objTaskState->final = $row;

			$this->saveTaskState($objTaskState);
		}
	}

	public function getTasksStates($id=0, $idProject){
		if((int)$idProject > 0){
			$this->sql ="	SELECT 
								id_tarefa_estado, id_usuario, id_projeto, nome, ordem, final, status, data
							FROM 
								tarefas_estados
							WHERE
								status = 1 AND id_projeto = ".$idProject;
			if($id > 0){
				$this->sql .= " AND id_tarefa_estado = ".$id;
			}

			$this->sql .= " ORDER BY ordem, id_tarefa_estado DESC";

			$this->result = parent::select($this->sql);
		}else{
			$this->result = null;
		}

		if(count($this->result) > 0){
			$i = 0;
			foreach($this->result as $row){
				$taskStateList[$i] = new TaskState();				
				$taskStateList[$i]->setDadosDB($row);				

				$i++;
			}
		}
		
		return $taskStateList;
	}

	public function deleteTaskState($id){
		if($id > 0){
			$rsTaskState = $this->getTasksStates($id,$_SESSION["PROJECT"]->id);

			if(count($rsTaskState) > 0){				
				$dados["status"] = 0;
				return parent::update("tarefas_estados", $dados, "id_tarefa_estado=".$id, "data");		
			}
		}

		return 0;
	}

/******************************************************************************************************************
Andamento das Tarefas Functions
******************************************************************************************************************/
	
	public function saveTaskGoing(TaskGoing $obj){
		if($obj != NULL){
			$dbObj = $obj->fieldsDBObj;
			unset($dbObj["id_tarefa_andamento"]);
			if($obj->id > 0){
				parent::update("tarefas_andamentos",$dbObj,"id_tarefa_andamento = ".$obj->id);
				return $obj->id;
			}else{
				return parent::insert("tarefas_andamentos",$dbObj,"data");
			}
		}else{
			return 0;
		}
	}

	public function getTaskGoing($id=0,$idTask=0){
	
		$this->sql ="	SELECT 
							ta.id_tarefa_andamento, ta.id_tarefa, ta.id_usuario, ta.quantidade_horas, ta.descricao, DATE_FORMAT(ta.data_andamento, '%d/%m/%Y') data_andamento, ta.status, DATE_FORMAT(ta.data, '%d/%m/%Y') data,
							u.nome nameUser, t.nome nameTask
						FROM 
							tarefas_andamentos ta					
						INNER JOIN
							tarefas t on t.id_tarefa = ta.id_tarefa
						INNER JOIN
							usuarios u on u.id_usuario = ta.id_usuario
						WHERE 
							ta.status = 1";

		if($id > 0)
			$this->sql .= "	AND ta.id_tarefa_andamento = ".$id;

		if($idTask > 0)
			$this->sql .= "	AND ta.id_tarefa = ".$idTask;

		$this->sql .= "	ORDER BY ta.data_andamento DESC";
		
		$this->result = parent::select($this->sql);
		$taskList = NULL;
		
		if(count($this->result) > 0){
			$i = 0;
			foreach($this->result as $row){
				$taskList[$i] = new TaskGoing();				
				$taskList[$i]->setDadosDB($row);				

				$i++;
			}
		}
		
		return $taskList;
	}
	
	public function deleteTaskGoing($id){
		if($id > 0){
			$rsTaskGoing = $this->getTaskGoing($id);

			if(count($rsTaskGoing) > 0){				
				$dados["status"] = 0;
				return parent::update("tarefas_andamentos", $dados, "id_tarefa_andamento=".$id, "data");		
			}
		}

		return 0;
	}
}

?>